<template>
  <div>
    <breadcrumb>
      <span slot="first">首页</span>
      <span slot="second">用户管理</span>
      <span slot="third">用户列表</span>
    </breadcrumb>
    <!-- 搜索框 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="userListParams.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机号码"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="updateStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑用户" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="userListParams.pagenum * 1" :page-sizes="[1, 2, 5, 10]" :page-size="userListParams.pagesize * 1"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="resetAddForm">
      <span>
        <el-form ref="addUserRef" :model="addUserList" label-width="90px" :rules="addUserRules">
          <el-form-item label="name" prop="username">
            <el-input v-model="addUserList.username"></el-input>
          </el-form-item>
          <el-form-item label="password" prop="password">
            <el-input v-model="addUserList.password"></el-input>
          </el-form-item>
          <el-form-item label="email" prop="email">
            <el-input v-model="addUserList.email"></el-input>
          </el-form-item>
          <el-form-item label="mobile" prop="mobile">
            <el-input v-model="addUserList.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserButton">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑操作对话框 -->
    <el-dialog title="编辑" :visible.sync="editdialogVisible" width="30%">
      <span>
        <el-form ref="editUserRef" :model="editUserList" label-width="70px" :rules="addUserRules">
          <el-form-item label="name">
            <el-input v-model="editUserList.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="email" prop="email">
            <el-input v-model="editUserList.email"></el-input>
          </el-form-item>
          <el-form-item label="mobile" prop="mobile">
            <el-input v-model="editUserList.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserButton()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除操作对话框 -->
    <el-dialog title="删除" :visible.sync="deletedialogVisible" width="30%">
      <span>
        是否删除？
      </span>
      <span slot="footer">
        <el-button @click="deletedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUserButton">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog @close="closeSaveRole" title="分配角色" :visible.sync="setRoledialogVisible" width="30%">
      <div>
        <p><span>用户名称：</span>{{this.userinfo.username}}</p>
        <p><span>用户当前角色：</span>{{this.userinfo.role_name}}</p>
        <el-select v-model="selectedRole" placeholder="请选择">
          <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { request } from '@/network/request'
import Breadcrumb from '@/components/common/Breadcrumb.vue'
export default {
  name: "Users",
  components: {
    Breadcrumb
  },
  data() {
    const validatePassMobile = (rule, value, callback) => {
      const re = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (re.test(value)) callback()
      callback(new Error("请输入正确的手机号码"))
    }
    const validatePassEmail = (rule, value, callback) => {
      const re = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (re.test(value)) callback()
      callback(new Error("请输入正确的电子邮箱"))
    }
    return {
      userListParams: {
        query: '',
        pagenum: '1',
        pagesize: "5"
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框显示隐藏
      dialogVisible: false,
      // 添加用户的表单的数据对象
      addUserList: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加用户的表单的验证规则对象
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validatePassEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePassMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑用户操作的对话框显示隐藏
      editdialogVisible: false,
      // 编辑用户的表单的数据对象
      editUserList: {},
      // 当前编辑操作用户id
      currentUserId: 0,
      // 控制删除操作对话框的显示隐藏
      deletedialogVisible: false,
      // 控制分配角色对话框的显示隐藏
      setRoledialogVisible: false,
      // 分配角色的用户信息
      userinfo: {},
      // 所有角色信息的列表
      rolesList: [],
      // 当前选择的角色
      selectedRole: ""
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await request({
        url: "/users",
        params: this.userListParams
      })
      if (res.meta.status !== 200) return this.$message.error("获取用户列表失败")
      this.userList = res.data.users
      this.total = res.data.total
      console.log(this.userList, this.total);
    },
    handleSizeChange(newSize) {
      this.userListParams.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.userListParams.pagenum = newPage
      this.getUserList()
    },
    // 更新用户状态，提交到数据库
    async updateStatus(info) {
      const { data: res } = await request({
        method: "put",
        url: `users/${info.id}/state/${info.mg_state}`
      })
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state
        return this.$message.error({
          message: "更新用户状态失败",
          duration: 1000
        })
      }
      return this.$message.success({
        message: "更新用户状态成功",
        duration: 1000
      })
    },
    // 监听添加用户表单关闭，重置表单
    resetAddForm() {
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户确定按钮
    addUserButton() {
      // 进行表单预验证
      this.$refs.addUserRef.validate(async result => {
        if (!result) return
        // 发送网络请求
        const { data: res } = await request({
          method: "post",
          url: "/users",
          data: this.addUserList
        })
        if (res.meta.status !== 201) return this.$message.error("添加用户失败")
        this.$message.success("添加用户成功")
        // 隐藏对话框
        this.dialogVisible = false
        // 刷新页面，重新请求用户列表数据
        this.getUserList()
      })
    },
    // 编辑用户确定按钮
    editUserButton() {
      // 表单预验证
      this.$refs.editUserRef.validate(async valid => {
        if (!valid) return
        // 发送网络请求
        const { data: res } = await request({
          method: "put",
          url: `users/${this.currentUserId}`,
          data: {
            id: this.editUserList.id,
            email: this.editUserList.email,
            mobile: this.editUserList.mobile,
          }
        })
        if (res.meta.status !== 200) return this.$message.error("更新用户信息失败")
        this.$message.success("更新用户信息成功")
        // 隐藏对话框
        this.editdialogVisible = false
        this.getUserList()
      })
    },
    // 编辑按钮
    async editUser(id) {
      this.editdialogVisible = true
      this.currentUserId = id
      // 请求数据
      const { data: res } = await request({
        url: `users/${id}`
      })
      if (res.meta.status !== 200) return
      this.editUserList = res.data
    },
    // 删除按钮
    deleteUser(id) {
      this.currentUserId = id
      this.deletedialogVisible = true
      console.log(this.currentUserId);
    },
    // 删除用户确定按钮
    async deleteUserButton() {
      // console.log(this.currentUserId);
      // 发送网络请求
      const { data: res } = await request({
        method: "delete",
        url: `users/${this.currentUserId}`
      })
      if (res.meta.status !== 200) {
        this.deletedialogVisible = false
        return this.$message.error("删除用户失败")
      }
      this.deletedialogVisible = false
      // 刷新页面
      this.getUserList()
      return this.$message.success("删除用户成功")
    },
    // 分配角色
    async setRole(userinfo) {
      this.userinfo = userinfo
      // 获取所有角色列表
      const { data: res } = await request("/roles")
      if (res.meta.status !== 200) return
      this.rolesList = res.data

      this.setRoledialogVisible = true
    },
    // 分配角色确定按钮
    async saveRole() {
      if (!this.selectedRole) return this.$message.error("请选择一个角色")
      // 发送网络请求
      const {data: res} = await request({
        method: "put",
        url: `users/${this.userinfo.id}/role`,
        data: {
          rid: this.selectedRole
        }
      })
      if (res.meta.status !== 200) return
      this.$message.success("分配角色成功")
      // 更新页面
      this.getUserList()
      this.setRoledialogVisible = false
    },
    // 监听分配角色对话框的关闭
    closeSaveRole() {
      this.selectedRole = '',
      this.userinfo = {}
    }
  },
}
</script>

<style lang='less' scoped>

</style>